package com.shop.web.servlet;

import java.beans.Encoder;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.shop.domain.User;
import com.shop.service.UserService;
import com.shop.utils.Constant;

/**
 * 激活码
 * @author Administrator
 *
 */
public class LoginServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = request.getContextPath();
		
		User user = new User();
		try {
			BeanUtils.populate(user, request.getParameterMap());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		UserService service = new UserService();
		User u = service.login(user);
		if (u != null) {
			request.getSession().setAttribute("loginUser", u);
			
			//写入cookie
			//if ("remember".equals(request.getParameter("remember"))) {
				//支持中文
				String usernname = URLEncoder.encode(u.getUsername(),"utf-8");
				Cookie nameCookie = new Cookie("username", usernname);
				nameCookie.setPath(path);
				nameCookie.setMaxAge(60*60*24);
				response.addCookie(nameCookie);
				Cookie passCookie = new Cookie("password", u.getPassword());
				passCookie.setPath(path);
				passCookie.setMaxAge(60*60*24);
				response.addCookie(passCookie);
				request.getRequestDispatcher("/index.jsp").forward(request, response);
			}
			
			
			//request.getRequestDispatcher("/500.jsp").forward(request, response);
//		}else {
//			request.setAttribute(Constant.MSG, "用户名或密码错误！登陆失败！");
//			request.getRequestDispatcher("/login.jsp").forward(request, response);
//		}
	}

}
